
package com.kweative.network;

import com.kweative.format.JsonFormat;
import com.kweative.format.UrlFormat;
import com.kweative.format.XmlFormat;
import com.kweative.type.Node;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.URL;
import java.util.HashMap;

/**
 *
 * @author henrik
 */
public class HttpRequest extends Request {
	private HttpType type = HttpType.GET;
	private HashMap<String,String> cookies = new HashMap<String, String>();
	private URL url;

    @Override
    public void read(InputStream in) throws IOException {
        boolean first = true;
        boolean headers = false;
        String line = "";
        String path = "/";
        String host = "";
        String protocol = "http";
        StringBuilder sb = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(in,"UTF-8"));
        String parts[];
        int port = 80;
        while ((line = br.readLine()) != null) {
            if (first) {
                if (line.trim().length() == 0) continue;
                parts = line.trim().split(" ");
                type = HttpType.valueOf(parts[0].trim());
                path = parts[1];
                first = false;
                headers = true;
            } else {
                if (headers && line.trim().length() == 0)
                    headers = false;
                if (headers) {
                    parts = line.trim().split(":",2);
                    String name = parts[0].trim();
                    String value = parts[1].trim();
                    headers().put(name.toLowerCase(),value);
                    if (name.equalsIgnoreCase("host")) {
                        if (value.indexOf(':') > -1) {
                            host = value.substring(0,value.indexOf(':'));
                            port = Integer.valueOf(value.substring(value.indexOf(':') + 1));
                        } else
                            host = value;
                    }
                } else {
                    //End of headers
                    break;
                }
            }
        }
        if (headers().containsKey("cookie")) {
            String cookieStr = headers().get("cookie");
            for(String nameValStr:cookieStr.split(";")) {
                String nameVal[] = nameValStr.trim().split("=",2);
                cookies.put(nameVal[0].trim(),nameVal[1].trim());
            }
        }
        if (type == HttpType.POST) {
            Integer len = 0;
            if (headers().containsKey("content-length")) {
                len = Integer.valueOf(headers().get("content-length"));
            } else {
                throw new IOException("Missing header: Content-length");
            }
            char[] body = new char[len];
            br.read(body);
            setBody(String.valueOf(body));
        }
        

        if (type == HttpType.POST) {
            String inFormat = "";
            if (headers().containsKey("lingua-input-format"))
                inFormat  = headers().get("lingua-input-format").toLowerCase();
            else
                inFormat = headers().get("content-type").toLowerCase();
            if (inFormat.indexOf("xml") > -1) {
                this.setFormat(new XmlFormat());
            } else if (inFormat.indexOf("json") > -1) {
                this.setFormat(new JsonFormat());
            } else if (inFormat.indexOf("urlencoded") > -1){
                this.setFormat(new UrlFormat());
            } else {
                throw new IOException("Unknown content type:" + inFormat);
            }
            this.setData(this.getFormat().parse(this.getBody()));
        } else if (type == HttpType.GET) {
            this.setFormat(new UrlFormat());
            if (path.indexOf("?") > -1) {
                parts = path.split("\\?",2);
                if (parts.length >= 2)
                    this.setData(this.getFormat().parse(parts[1]));
            }
        }
            
        //if (host.length() == 0)
            //throw new IOException("No hostname found");
        this.url = new URL(protocol,host,port,path);
    }
    public String getCookie(String key) {
        return cookies.get(key);
    }
    public HttpType getType() {
        return type;
    }

    public void setType(HttpType type) {
        this.type = type;
    }

    public URL getUrl() {
        return url;
    }

    public void setUrl(URL url) {
        this.url = url;
    }

    @Override
    public void clear() {
        super.clear();
        this.url = null;
        this.type = HttpType.GET;
    }


    

    public enum HttpType {
        POST,GET,PUT,DELETE
    }
}
